package com.example.springboot.controller.exception;

import com.example.springboot.common.ResultVO;
import com.example.springboot.common.UnauthorizedException;
import org.apache.shiro.ShiroException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 自定义异常处理（全局异常处理）
 */
@RestControllerAdvice
public class ExceptionController {

    /**
     * 捕捉shiro异常
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(ShiroException.class)
    public ResultVO handle401(ShiroException e){
        return new ResultVO(401, e.getMessage(), null);
    }

    /**
     * 捕捉UnauthorizedException异常
     * @return
     */
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(UnauthorizedException.class)
    public ResultVO handle401(){
        return new ResultVO(401, "Unauthorized", null);
    }

    /**
     * 捕捉其他异常
     * @param request
     * @param ex
     * @return
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(Exception.class)
    public ResultVO globalException(HttpServletRequest request, Throwable ex){
        return new ResultVO(getStatus(request).value(), ex.getMessage(), null);
    }

    private HttpStatus getStatus(HttpServletRequest request){
        Integer statusCode = (Integer)request.getAttribute("javax.servlet.error.status_code");
        if(statusCode == null){
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return HttpStatus.valueOf(statusCode);
    }

}
